<!--
 * @Author: thats-all-right-ha-ha 8280209+thats-all-right-ha-ha@user.noreply.gitee.com
 * @Date: 2024-06-05 10:33:52
 * @LastEditors: thats-all-right-ha-ha 8280209+thats-all-right-ha-ha@user.noreply.gitee.com
 * @LastEditTime: 2024-06-11 10:52:49
 * @FilePath: \vue-admin-template\src\views\banner\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="banner">
    <!-- 添加轮播图 -->
    <el-button @click="addBanner">添加轮播图</el-button>
    <!-- 表格主体 -->
    <el-table :data="bannerList" border style="width: 100%">
      <el-table-column label="id" width="180">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="carousel" label="图片" width="400">
        <template slot-scope="scope">
          <img :src="scope.row.carousel" alt="" width="300px">
        </template>
      </el-table-column>
      <el-table-column prop="date" label="日期">
        <template slot-scope="scope">
          最后修改日期: {{ scope.row.date }}
        </template>
      </el-table-column>
      <el-table-column prop="is_use" label="启用状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_use"
            style="display: block"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="启用"
            inactive-text="禁用"
            @change="show(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="update(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="remove(scope.row._id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑对话框 -->
    <el-dialog :title="addOrUpdate" :visible.sync="isShow">
      <!-- 上传组件 -->
      <el-upload
        ref="upload"
        class="upload-demo"
        action="action"
        :limit="1"
        :auto-upload="false"
        :http-request="reqBanner"
        :file-list="newBanner"
        :on-change="choose"
        :before-upload="getFile"
        :on-remove="unChoose"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <el-switch
        v-model="is_use"
        style="display: block"
        active-color="#13ce66"
        inactive-color="#ff4949"
        active-text="启用"
        inactive-text="禁用"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="commit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBannerList, bannerSwitch, changBanner, addBanner, removeBanner } from '@/api/banner'
export default {
  name: 'BannerManage',
  data() {
    return {
      bannerList: [],
      isShow: false,
      newBanner: [],
      id: '',
      is_use: false,
      file: '',
      haveImg: false,
      add: false
    }
  },
  computed: {
    addOrUpdate() {
      return this.add ? '添加' : '更新'
    }
  },
  created() {
    this.getBanner()
  },
  methods: {
    async getBanner() {
      const res = await getBannerList()
      this.bannerList = res.data
      console.log(this.bannerList, '111')
    },
    // 改变轮播图状态
    async show(val) {
      const { _id, is_use } = val
      const res = await bannerSwitch({ id: _id, is_use })
      if (res.code === 20000) {
        this.$message({
          type: 'success',
          message: res.message
        })
      } else {
        this.$message({
          type: 'error',
          message: res.message
        })
      }
    },
    // 更新banner
    update(val) {
      this.add = false
      this.isShow = true
      this.id = val._id
    },
    // 上传文件到服务器
    async reqBanner() {
      for (const pair of this.file.entries()) {
        console.log(`${pair[0]}, ${pair[1] instanceof File ? pair[1].name : pair[1]}`)
      }
      try {
        if (!this.add) {
          const res = await changBanner(this.id, this.file)
          if (res.code === 20000) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.isShow = false
            this.$refs.upload.clearFiles()
            this.haveImg = false
            this.getBanner()
            this.is_use = false
          }
        }

        if (this.add) {
          const res = await addBanner(this.file)
          if (res.code === 20000) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.isShow = false
            this.$refs.upload.clearFiles()
            this.haveImg = false
            this.getBanner()
            this.is_use = false
          }
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 提交更新
    commit() {
      if (!this.haveImg) {
        this.$message({
          message: '请选择文件',
          type: 'error'
        })
        return false
      }
      this.$refs.upload.submit()
    },
    // 选择文件
    choose(file) {
      this.haveImg = true
    },
    unChoose() {
      this.haveImg = false
    },
    // 获取文件 before-upload
    getFile(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      const typeList = ['jpg', 'jpeg', 'png']
      if (!typeList.includes(type)) {
        this.$message({
          type: 'error',
          message: '文件类型不符'
        })
        return false
      }
      console.log(file)
      if (file.size / 1024 > 500) {
        this.$message({
          type: 'error',
          message: '图片大小不能超过500kb'
        })
        return false
      }
      const fileData = new FormData()
      fileData.append('files', file)
      fileData.append('is_use', this.is_use)
      this.file = fileData
    },
    // 添加轮播图
    addBanner() {
      this.isShow = true
      this.add = true
    },
    // 删除轮播图
    remove(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await removeBanner(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getBanner()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.banner {
  padding: 30px;
}
</style>
